package host

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/nick/vdamtools/apps/dashboard/cmd"
	"github.com/nick/vdamtools/apps/monitor"
	"github.com/nick/vdamtools/pkg/loggerv"
	"go.uber.org/zap"
)

func Host(c *gin.Context) {
	var data monitor.ServerData
	if err := c.BindJSON(&data); err != nil {
		fmt.Println("Error binding JSON:", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Error binding JSON"})
		return
	}
	loggerv.Logger.Info("POST Host", zap.Any("ReceivedData", data))
	handleServerData(data)
	c.JSON(http.StatusOK, gin.H{
		"status":  "OK",
		"message": "Data received",
	})

}

func GetHost(c *gin.Context) {
	loggerv.Logger.Info("GET HOST")
	hosts := handleGetHosts()
	c.JSON(http.StatusOK, gin.H{
		"status":  "OK",
		"message": "Data received",
		"data":    hosts,
	})
}

func LastIndexes(c *gin.Context) {
	loggerv.Logger.Info("GET LastIndexes")
	data, err := handleLastIndexes()
	if err == nil {
		c.JSON(http.StatusOK, gin.H{
			"status":  "OK",
			"message": "Data received",
			"data":    data,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"status":  "ERROR",
			"message": "read data failed.",
		})
	}

}

func GetindexsByTimes(c *gin.Context) {

	var cmd cmd.CmdGetindexsByTimes

	startTimeStr := c.Query("startTime")
	endTimeStr := c.Query("endTime")
	var err error
	cmd.StartTime, err = time.Parse("2006-01-02T15:04:05", startTimeStr)
	if err != nil {
		fmt.Println("Error parsing startTime:", err)
		c.JSON(http.StatusOK, gin.H{
			"status":  "ERROR",
			"message": "Error parsing startTime",
		})
		return
	}

	cmd.EndTime, err = time.Parse("2006-01-02T15:04:05", endTimeStr)
	if err != nil {
		fmt.Println("Error parsing endTime:", err)
		c.JSON(http.StatusOK, gin.H{
			"status":  "ERROR",
			"message": "Error parsing endTime",
		})
		return
	}

	loggerv.Logger.Info("GET GetindexsByTimes", zap.Any("cmd", cmd), zap.Any("startTimeStr", startTimeStr), zap.Any("endTimeStr", endTimeStr))

	data, err := handleGetindexsByTimes(cmd)
	if err == nil {
		c.JSON(http.StatusOK, gin.H{
			"status":  "OK",
			"message": "Data received",
			"data":    data,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"status":  "ERROR",
			"message": "read data failed.",
		})
	}

}
